<template>
  <div class="category-manager">
    <div class="header">
      <el-row>
        <el-button
          v-waves
          type="primary"
          icon="el-icon-edit"
          circle
          @click="handlerAdd"
        >新增</el-button>
      </el-row>
    </div>
    <div class="body">
      <el-table
        v-loading="listLoading"
        :data="categoryList"
        style="width: 100%"
      >
        <el-table-column label="编号" prop="id" />
        <el-table-column label="保险类别" prop="categoryName">
          <template slot-scope="scope">
            <el-input
              v-if="scope.row.isNameSelected"
              v-model="scope.row.categoryName"
              v-focus
              minlength="3"
              maxlength="10"
              @focus="focusEvent(scope.row, scope.$index, scope.column)"
              @blur="blurEvent(scope.row, scope.$index, scope.column)"
              @keyup.enter.native="
                blurEvent(scope.row, scope.$index, scope.column)
              "
            />
            <p v-else @click="cellClick(scope.row, scope.column)">
              {{ scope.row.categoryName }}
            </p>
          </template>
        </el-table-column>
        <el-table-column align="right">
          <!-- 注意：这里的 solt-scope 不要遗漏 -->
          <template slot="header" slot-scope="scope">
            <el-input
              v-model.lazy="keyword"
              size="mini"
              placeholder="输入关键字后按回车搜索"
              @change="handlerSearch(scope.row)"
            />
          </template>
          <template slot-scope="scope">
            <template>
              <el-popconfirm
                title="操作不可逆，确认删除？"
                icon-color="red"
                icon="el-icon-info"
                @confirm="handlerDel(scope.row)"
              >
                <el-button
                  slot="reference"
                  v-waves
                  size="mini"
                  type="danger"
                >删除</el-button>
              </el-popconfirm>
            </template>
            <el-button
              v-waves
              size="mini"
              type="primary"
              @click="handlerEdit(scope.row)"
            >修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.pageNo"
        :limit.sync="listQuery.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script>
import {
  getCateList,
  deleteCateList,
  createCateList,
  editCateList
} from '@/api/category'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
export default {
  name: 'ProCategoryManager',
  components: {
    Pagination
  },
  directives: {
    waves,
    // 获取焦点指令
    focus: {
      inserted: function(el) {
        el.querySelector('input').focus()
      }
    }
  },
  data() {
    return {
      categoryList: [],
      // 缓存数据
      tempList: {},
      keyword: '',
      // 分页查询数据
      total: 0,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        categoryName: ''
      },
      // loading 效果
      listLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    getList() {
      // loading 样式
      this.listLoading = true
      getCateList(this.listQuery).then((res) => {
        // 在此处对数据做处理，为name列都加上是否被选中的flag
        this.categoryList = res.data.rows.map((v) => {
          return { ...v, isNameSelected: false }
        })
        // this.categoryList = res.data.rows;
        this.tempList = Array.from(this.categoryList)
        this.total = Number(res.data.total)
        setTimeout(() => {
          this.listLoading = false
        }, 500)
      })
    },
    async handlerDel(row) {
      const res = await deleteCateList(row.id)
      if (res.code === 200) {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success'
        })
        // 删除成功后，返回第一页
        this.listQuery.pageNo = 1
        this.getList()
      } else {
        this.$notify.error({
          title: '错误',
          message: '呜呜呜...出错了'
        })
      }
    },
    handlerSearch() {
      this.categoryList = Array.from(
        this.tempList.filter((v) => v.categoryName.includes(this.keyword))
      )
    },
    // 新增类别
    handlerAdd() {
      this.$prompt('只能录入中文、字母和数字', '请输入新增类别', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/,
        inputErrorMessage: '类别格式不正确'
      })
        .then(async({ value }) => {
          const data = {
            pageNo: this.listQuery.pageNo,
            pageSize: this.listQuery.pageSize,
            categoryName: value
          }
          const res = await createCateList(data)
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '新增类别成功'
            })
            this.listQuery.pageNo = 1
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: '呜呜呜...出错了'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          })
        })
    },
    // 聚焦与失焦处理
    // 双击时，将选中状态设置为true
    cellClick(row, column) {
      if (column.label === '保险类别') {
        row.isNameSelected = !row.isNameSelected
      }
    },
    focusEvent(row, index, column) {
      if (column.label === '保险类别') {
        row.oldName = row.categoryName
      }
    },
    // 输入框失去焦点触发,此处用提示框提示修改
    blurEvent(row, curIndex, column) {
      if (column.label === '保险类别') {
        row.isNameSelected = !row.isNameSelected
        if (row.categoryName !== row.oldName) {
          this.$message({
            message: '已更改，请点击修改按钮完成修改',
            type: 'success',
            duration: 2000
          })
        } else {
          this.$message({
            message: '未更改内容',
            type: 'info',
            duration: 2000
          })
        }
      }
    },
    // 处理修改事件
    async handlerEdit(row) {
      const query = {
        id: row.id,
        pageNo: this.listQuery.pageNo,
        pageSize: this.listQuery.pageSize,
        categoryName: row.categoryName
      }
      const res = await editCateList(query)
      if (res.code === 200) {
        this.$notify({
          message: '修改成功',
          type: 'success'
        })
        this.getList()
      } else {
        this.$notify({
          message: '呜呜呜...出错了',
          type: 'error'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.category-manager {
  margin: 20px 20px 0;
  border-radius: 10px;
  box-shadow: rgba(9, 30, 66, 0.25) 0px 1px 1px,
    rgba(9, 30, 66, 0.13) 0px 0px 1px 1px;
  overflow: hidden;
  .header {
    .el-button {
      border-radius: 0;
    }
  }
  .footer {
    text-align: center;
  }
}
</style>
